import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, DatePicker, Select, Button, Table, Space, message, Progress, Tag } from 'antd';
import { ProCard } from '@ant-design/pro-components';
import { 
  ApiOutlined, 
  ClockCircleOutlined, 
  ExclamationCircleOutlined, 
  DownloadOutlined,
  ReloadOutlined,
  DatabaseOutlined,
  CloudServerOutlined,
  MonitorOutlined 
} from '@ant-design/icons';
import { EchartsLine, EchartsColumn, EchartsPie, EchartsArea, EchartsGauge } from '@/components/Charts';
import dayjs from 'dayjs';
import { 
  getSystemStatistics, 
  getSystemPerformanceMetrics, 
  getApiUsageStatistics,
  exportStatisticsData 
} from '@/services/statisticsApi';

const { RangePicker } = DatePicker;
const { Option } = Select;

const SystemStats: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [timeRange, setTimeRange] = useState<STATISTICS.TimeRange>('month');
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
    dayjs().subtract(30, 'day'),
    dayjs()
  ]);
  const [statistics, setStatistics] = useState<STATISTICS.SystemStatistics | null>(null);

  // 获取统计数据
  const fetchStatistics = async () => {
    setLoading(true);
    try {
      const params: STATISTICS.StatisticsQueryParams = {
        time_range: timeRange,
        start_date: dateRange[0].format('YYYY-MM-DD'),
        end_date: dateRange[1].format('YYYY-MM-DD'),
        granularity: 'day'
      };

      const response = await getSystemStatistics(params);
      if (response.code === 200) {
        setStatistics(response.data);
      } else {
        message.error(response.message || '获取系统统计数据失败');
      }
    } catch (error) {
      console.error('获取系统统计数据失败:', error);
      message.error('获取统计数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 导出数据
  const handleExport = async (type: 'excel' | 'csv' | 'pdf') => {
    try {
      const params: STATISTICS.ExportParams = {
        type,
        data_type: 'system',
        time_range: timeRange,
        start_date: dateRange[0].format('YYYY-MM-DD'),
        end_date: dateRange[1].format('YYYY-MM-DD'),
        include_charts: true
      };

      await exportStatisticsData(params);
      message.success(`${type.toUpperCase()}文件导出成功`);
    } catch (error) {
      console.error('导出失败:', error);
      message.error('导出失败');
    }
  };

  useEffect(() => {
    fetchStatistics();
  }, [timeRange, dateRange]);

  // 响应时间趋势图配置
  const responseTimeTrendConfig = {
    data: statistics?.performance_metrics.response_time_trend || [],
    xField: 'date',
    yField: 'value',
    smooth: true,
    color: '#1890ff',
    point: {
      size: 3,
      shape: 'circle',
    },
    tooltip: {
      formatter: (datum: any) => ({
        name: '响应时间',
        value: `${datum.value}ms`,
      }),
    },
  };

  // API调用量趋势图配置
  const apiCallsTrendConfig = {
    data: statistics?.performance_metrics.api_calls_trend || [],
    xField: 'date',
    yField: 'value',
    smooth: true,
    color: '#52c41a',
    area: {
      style: {
        fill: 'l(270) 0:#ffffff 0.5:#95de64 1:#52c41a',
      },
    },
  };

  // 错误率趋势图配置
  const errorRateTrendConfig = {
    data: statistics?.performance_metrics.error_rate_trend || [],
    xField: 'date',
    yField: 'value',
    smooth: true,
    color: '#ff4d4f',
    point: {
      size: 3,
      shape: 'circle',
    },
    tooltip: {
      formatter: (datum: any) => ({
        name: '错误率',
        value: `${datum.value}%`,
      }),
    },
  };

  // API使用统计表格列配置
  const apiUsageColumns = [
    {
      title: '接口路径',
      dataIndex: 'endpoint',
      key: 'endpoint',
      width: 200,
      ellipsis: true,
    },
    {
      title: '请求方法',
      dataIndex: 'method',
      key: 'method',
      width: 80,
      render: (method: string) => (
        <Tag color={
          method === 'GET' ? 'blue' : 
          method === 'POST' ? 'green' : 
          method === 'PUT' ? 'orange' : 
          method === 'DELETE' ? 'red' : 'default'
        }>
          {method}
        </Tag>
      ),
    },
    {
      title: '调用次数',
      dataIndex: 'call_count',
      key: 'call_count',
      width: 100,
      render: (count: number) => count.toLocaleString(),
    },
    {
      title: '平均响应时间',
      dataIndex: 'average_response_time',
      key: 'average_response_time',
      width: 120,
      render: (time: number) => `${time}ms`,
    },
    {
      title: '错误次数',
      dataIndex: 'error_count',
      key: 'error_count',
      width: 100,
      render: (count: number) => count.toLocaleString(),
    },
    {
      title: '错误率',
      dataIndex: 'error_rate',
      key: 'error_rate',
      width: 100,
      render: (rate: number) => (
        <Tag color={rate < 1 ? 'green' : rate < 5 ? 'orange' : 'red'}>
          {rate.toFixed(2)}%
        </Tag>
      ),
    },
  ];

  // 存储使用情况仪表盘配置
  const storageGaugeConfig = {
    percent: (statistics?.storage_usage.usage_percentage || 0) / 100,
    color: {
      range: ['#30BF78', '#FAAD14', '#F4664A'],
      rangeColor: ['#30BF78', '#FAAD14', '#F4664A'],
    },
    indicator: {
      pointer: {
        style: {
          stroke: '#D0D0D0',
        },
      },
      pin: {
        style: {
          stroke: '#D0D0D0',
        },
      },
    },
    statistic: {
      content: {
        style: {
          fontSize: '36px',
          lineHeight: '36px',
        },
        formatter: () => `${(statistics?.storage_usage.usage_percentage || 0).toFixed(1)}%`,
      },
    },
  };

  return (
    <div style={{ padding: '24px' }}>
      {/* 页面标题和操作栏 */}
      <ProCard
        title="系统统计"
        extra={
          <Space>
            <Select
              value={timeRange}
              onChange={setTimeRange}
              style={{ width: 120 }}
            >
              <Option value="today">今天</Option>
              <Option value="yesterday">昨天</Option>
              <Option value="week">本周</Option>
              <Option value="month">本月</Option>
              <Option value="quarter">本季度</Option>
              <Option value="year">本年</Option>
              <Option value="custom">自定义</Option>
            </Select>
            {timeRange === 'custom' && (
              <RangePicker
                value={dateRange}
                onChange={(dates) => dates && setDateRange(dates)}
                format="YYYY-MM-DD"
              />
            )}
            <Button
              icon={<ReloadOutlined />}
              onClick={fetchStatistics}
              loading={loading}
            >
              刷新
            </Button>
            <Button.Group>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport('excel')}
              >
                导出Excel
              </Button>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport('csv')}
              >
                导出CSV
              </Button>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport('pdf')}
              >
                导出PDF
              </Button>
            </Button.Group>
          </Space>
        }
        style={{ marginBottom: 24 }}
      />

      {/* 概览统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="总API调用"
              value={statistics?.overview.total_api_calls || 0}
              prefix={<ApiOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="平均响应时间"
              value={statistics?.overview.average_response_time || 0}
              suffix="ms"
              prefix={<ClockCircleOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="错误率"
              value={statistics?.overview.error_rate || 0}
              precision={2}
              suffix="%"
              prefix={<ExclamationCircleOutlined />}
              valueStyle={{ color: '#ff4d4f' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="系统正常运行时间"
              value={statistics?.overview.uptime_percentage || 0}
              precision={2}
              suffix="%"
              prefix={<MonitorOutlined />}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 系统性能趋势图表 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} lg={8}>
          <ProCard title="响应时间趋势" loading={loading}>
            <EchartsLine {...responseTimeTrendConfig} height={250} />
          </ProCard>
        </Col>
        <Col xs={24} lg={8}>
          <ProCard title="API调用量趋势" loading={loading}>
            <EchartsArea {...apiCallsTrendConfig} height={250} />
          </ProCard>
        </Col>
        <Col xs={24} lg={8}>
          <ProCard title="错误率趋势" loading={loading}>
            <EchartsLine {...errorRateTrendConfig} height={250} />
          </ProCard>
        </Col>
      </Row>

      {/* 系统资源使用情况 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} lg={8}>
          <ProCard title="存储使用情况" loading={loading}>
            <EchartsGauge {...storageGaugeConfig} height={250} />
            <div style={{ marginTop: 16, textAlign: 'center' }}>
              <Space direction="vertical" size="small">
                <div>数据库大小: {((statistics?.storage_usage.database_size || 0) / 1024 / 1024 / 1024).toFixed(2)} GB</div>
                <div>文件存储: {((statistics?.storage_usage.file_storage_size || 0) / 1024 / 1024 / 1024).toFixed(2)} GB</div>
                <div>缓存使用: {((statistics?.storage_usage.cache_usage || 0) / 1024 / 1024).toFixed(2)} MB</div>
              </Space>
            </div>
          </ProCard>
        </Col>
        <Col xs={24} lg={8}>
          <ProCard title="内存使用趋势" loading={loading}>
            <EchartsArea
              data={statistics?.performance_metrics.memory_usage_trend || []}
              xField="date"
              yField="value"
              smooth={true}
              color="#fa8c16"
              area={{
                style: {
                  fill: 'l(270) 0:#ffffff 0.5:#ffd591 1:#fa8c16',
                },
              }}
              height={250}
            />
          </ProCard>
        </Col>
        <Col xs={24} lg={8}>
          <ProCard title="CPU使用趋势" loading={loading}>
            <EchartsArea
              data={statistics?.performance_metrics.cpu_usage_trend || []}
              xField="date"
              yField="value"
              smooth={true}
              color="#722ed1"
              area={{
                style: {
                  fill: 'l(270) 0:#ffffff 0.5:#d3adf7 1:#722ed1',
                },
              }}
              height={250}
            />
          </ProCard>
        </Col>
      </Row>

      {/* API使用统计和错误分析 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} lg={16}>
          <ProCard title="API使用统计" loading={loading}>
            <Table
              columns={apiUsageColumns}
              dataSource={statistics?.api_usage || []}
              rowKey="endpoint"
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
              }}
              scroll={{ x: 800 }}
              size="small"
            />
          </ProCard>
        </Col>
        <Col xs={24} lg={8}>
          <ProCard title="错误类型分布" loading={loading}>
            <EchartsPie
              data={statistics?.error_distribution || []}
              angleField="count"
              colorField="error_type"
              radius={0.8}
              label={{
                type: 'outer',
                content: '{name}: {percentage}',
              }}
              interactions={[{ type: 'element-active' }]}
              height={300}
            />
          </ProCard>
        </Col>
      </Row>

      {/* 用户会话分析 */}
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <ProCard title="会话时长分布" loading={loading}>
            <EchartsColumn
              data={statistics?.user_sessions.session_duration_distribution || []}
              xField="duration_range"
              yField="count"
              color="#52c41a"
              columnWidthRatio={0.8}
              meta={{
                duration_range: { alias: '会话时长' },
                count: { alias: '会话数量' },
              }}
              height={300}
            />
          </ProCard>
        </Col>
        <Col xs={24} lg={12}>
          <ProCard title="并发用户数趋势" loading={loading}>
            <EchartsLine
              data={statistics?.user_sessions.concurrent_users_trend || []}
              xField="date"
              yField="value"
              smooth={true}
              color="#1890ff"
              point={{
                size: 3,
                shape: 'circle',
              }}
              tooltip={{
                formatter: (datum: any) => ({
                  name: '并发用户数',
                  value: `${datum.value}人`,
                }),
              }}
              height={300}
            />
          </ProCard>
        </Col>
      </Row>
    </div>
  );
};

export default SystemStats;
